package com.unionServer.models;

import com.unionServer.common.ActualBinaryConvertor;
import com.unionServer.common.BinaryIntConvertor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @description:
 * @author: wangxinal
 * @time: 2022/1/13 17:11
 */
@Slf4j
public class MessageHead {
    @Getter
    @Setter
    HashMap<String, Object> messageHeadMap = new HashMap<String, Object> ();

    ActualBinaryConvertor actualBinaryConvertor = new ActualBinaryConvertor() ;

    BinaryIntConvertor binaryIntConvertor = new BinaryIntConvertor() ;

    public MessageHead (byte[] msg, Element headElm) throws IOException {
        BufferedInputStream in = null;
        in = new BufferedInputStream(new ByteArrayInputStream(msg));
        Iterator itr = headElm.elementIterator();

        while(itr.hasNext()) {
            Element curNode = (Element)itr.next();
            int length = Integer.parseInt(curNode.attributeValue("length"));
            byte[] temp = new byte[length];
            in.read(temp);
            if (curNode.attributeValue("mode") != null && curNode.attributeValue("mode").equals("ACT_BIN") ){
                String tempStr = new String(actualBinaryConvertor.getFromBcd(temp),StandardCharsets.US_ASCII ).trim();
                messageHeadMap.put(curNode.getQName().getName(), tempStr);
            }if (curNode.attributeValue("mode") != null && curNode.attributeValue("mode").equals("BIN_INT") ){
                String tempStr = new String(binaryIntConvertor.getFromBcd(temp),StandardCharsets.US_ASCII ).trim();
                messageHeadMap.put(curNode.getQName().getName(), tempStr);
            }else {
                messageHeadMap.put(curNode.getQName().getName(), new String(temp, StandardCharsets.US_ASCII));
            }

        }
    }
    byte[] getFromBcd(byte[] arg0) {
        StringBuilder sb = new StringBuilder();
        byte[] arr$ = arg0;
        int len$ = arg0.length;

        for(int i$ = 0; i$ < len$; ++i$) {
            Byte b = arr$[i$];
            String tmp = Integer.toBinaryString(b & 255);
            int length = tmp.length();
            if (length < 8) {
                for(int j = 0; j < 8 - length; ++j) {
                    sb.append("0");
                }
            }

            sb.append(tmp);
        }

        return sb.toString().getBytes();
    }

    @Override
    public String toString() {
        for (Map.Entry<String,Object> entry : messageHeadMap.entrySet() ){
            log.info(entry.getKey() + " - " + entry.getValue() );
        }
        return "MessageHead{" +
                "messageHeadMap=" + messageHeadMap +
                '}';
    }
}
